package com.chen.stopwatch.History;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chen.stopwatch.R;
import com.chen.stopwatch.StroageManager;
import com.chen.stopwatch.StroageManager.HistoryDateItem;
import com.chen.stopwatch.utils.Utils;

public class HistoryDataAdapter extends BaseAdapter {
	protected LayoutInflater mInflater = null;

	public HistoryDataAdapter(Context context) {
		if (null != context)
			mInflater = LayoutInflater.from(context);
	}

	public void destroy() {
		mInflater = null;
	}

	public int getCount() {
		return StroageManager.getInstance().getHistoryDayAndClockCount();
	}

	public Object getItem(int position) {
		return StroageManager.getInstance().getDayAndClockItem(position);
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		try {
			if (null == mInflater)
				return convertView;

			if (null == convertView) {
				convertView = mInflater.inflate(R.layout.history_item, null);
				if (null == convertView)
					return null;
			}

			fillHolder(createHolder(convertView), position);
			return convertView;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return convertView;
	}

	protected void fillHolder(View convertView, int position) {
		if (null == convertView)
			return;
		HistoryHolder holder = (HistoryHolder) convertView.getTag();
		String text = "";
		HistoryDateItem item = (HistoryDateItem) getItem(position);
		if (item.isDateDay) {
			text = Utils.formatStandardDateDay(item.time);
			holder.clock.setVisibility(View.GONE);
			holder.dayLayout.setVisibility(View.VISIBLE);
			holder.day.setText(text);
		} else {
			text = Utils.formatStandardDateClock(item.time);
			holder.dayLayout.setVisibility(View.GONE);
			holder.clock.setVisibility(View.VISIBLE);
			holder.clock.setText(text);
		}
	}

	protected View createHolder(View convertView) {
		if (null == convertView.getTag()) {
			HistoryHolder holder = new HistoryHolder();
			holder.dayLayout = (RelativeLayout) convertView.findViewById(R.id.insert_day_layout);
			holder.day = (TextView) convertView.findViewById(R.id.insert_day);
			holder.clock = (TextView) convertView.findViewById(R.id.insert_clock);
			convertView.setTag(holder);
		}

		return convertView;
	}
}
